import React from 'react';
import _ from 'underscore';
import View from 'lib/View.jsx';
import DropdownList from '../common/DropdownList.jsx';
import Layout from '../common/layout.jsx';
import Card from 'lib/components/card.jsx';
import Loading from 'lib/util/defaultLoadingElement.jsx';
import MainViewScope from './MainViewScope.es6';

class MainView extends View {

  handleChange({id}) {
    this.props.history.pushState(null, `/detail/${id}`);
  }

  render() {
    let current = _.find(this.state.elements, (element) => {
      return element.id === +this.props.params.id;
    }) || {};

    if (this.state.loading) {
      return (
        <Layout title="关键元素" subtitle="关键请求">
          <Loading />
        </Layout>
      )
    }

    return (
      <Layout title="关键元素" subtitle="关键请求">
        {
          this.state.elements.length === 0 ? (
            <div className="pure-g">
              <div className="pure-u-1-1">
                <div className="card">
                  <Card>
                    还没有关键元素，<a href="elements">快去添加吧</a>
                  </Card>
                </div>
              </div>
            </div>
          ) : (
            <div className="element-detail">
              <div className="pure-g">
                <div className="element-dropdown-list pure-u-1 pure-u-xl-1-3">
                  <DropdownList current={current} list={this.state.elements} onChanging={ this.handleChange.bind(this) } />
                  <a href="elements" style={{
                    display: 'inline-block',
                    verticalAlign: 'top',
                    marginTop: '23px' }}>
                    <i className="iconfont goto-elements" data-tip="设置关键元素">&#xe61e;</i>
                  </a>
                </div>
              </div>
              { React.cloneElement(this.props.children, { regexp: current.regexp, routeParams: this.props.params, key: this.getHandlerKey() }) }
            </div>
          )
        }
      </Layout>
    );
  }
}

MainView.defaultProps = {
  Scope: MainViewScope
};

export default MainView;
